//
//  CustomTransitionContext.m
//  Objective-C
//
//  Created by 陆承东 on 2018/7/7.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "CustomTransitionContext.h"

@interface CustomTransitionContext()

@property (nonatomic, strong) NSDictionary *viewControllers;
@property (nonatomic, assign) CGRect disappearingFromRect;
@property (nonatomic, assign) CGRect appearingFromRect;
@property (nonatomic, assign) CGRect disappearingToRect;
@property (nonatomic, assign) CGRect appearingToRect;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, assign) UIModalPresentationStyle presentationStyle;

@end

@implementation CustomTransitionContext

- (instancetype)initWithFromVC:(UIViewController *)fromVC toVC:(UIViewController *)toVC goingRight:(BOOL)goingRight {
    self = [super init];
    
    if (self) {
        NSAssert([fromVC isViewLoaded] && fromVC.view.subviews, @"The fromVC's view must reside in the container view upon initializing the transition context.");
        
        self.presentationStyle = UIModalPresentationCustom;
        self.containerView = fromVC.view.superview;
        self.viewControllers = @{
                                 UITransitionContextFromViewControllerKey: fromVC,
                                 UITransitionContextToViewControllerKey: toVC
                                 };
        CGFloat travelDistance = goingRight ? -self.containerView.bounds.size.width : self.containerView.bounds.size.width;
        self.disappearingFromRect = self.appearingToRect = self.containerView.bounds;
        self.disappearingToRect = CGRectOffset(self.containerView.bounds, travelDistance, 0);
        self.appearingToRect = CGRectOffset(self.containerView.bounds, -travelDistance, 0);
    }
    
    return self;
}

- (CGRect)initialFrameForViewController:(UIViewController *)vc {
    if (vc == [self viewControllerForKey:UITransitionContextFromViewControllerKey]) {
        return self.disappearingToRect;
    }
    
    return self.appearingToRect;
}

- (CGRect)finalFrameForViewController:(UIViewController *)vc {
    if (vc == [self viewControllerForKey:UITransitionContextFromViewControllerKey]) {
        return self.disappearingToRect;
    }
    
    return self.appearingToRect;
}

- (UIViewController *)viewControllerForKey:(UITransitionContextViewControllerKey)key {
    return self.viewControllers[key];
}

- (void)completeTransition:(BOOL)didComplete {
    if (self.completionBlock) {
        self.completionBlock(didComplete);
    }
}

- (BOOL)transitionWasCancelled {
    return false;
}

- (void)updateInteractiveTransition:(CGFloat)percentComplete {
    
}

- (void)finishInteractiveTransition {
    
}

- (void)cancelInteractiveTransition {
    
}

- (nullable __kindof UIView *)viewForKey:(nonnull UITransitionContextViewKey)key {
    return nil;
}

@synthesize targetTransform;

@end
